#import <UIKit/UIKit.h>
#import "WXApi.h"
#import "social.h"
#import "wechat.h"

@implementation WechatPlatformProvider
{
    SocialRequestCompletionHandler authHandler;
    SocialRequestCompletionHandler shareHandler;
}
-(id)init
{
    return [super init];
}

-(void)launch:(NSDictionary *)launchOptions{
}
-(void)setAppKey:(NSString *)appKey
   withAppSecret:(NSString *)appSecret
 withRedirectURL:(NSString *)redirectURL{
    NSString *link = [[NSBundle mainBundle].infoDictionary objectForKey:@"WechatLink"];
    [WXApi registerApp:appKey universalLink:link];
    self->_appKey = appKey;
    self->_appSecret = appSecret;
}
-(void)AuthorizeWithUserInfo:(NSDictionary *)userInfo
       withCompletionHandler:(SocialRequestCompletionHandler)completionHandler{
    //构造SendAuthReq结构体
    NSLog(@"weixin login");
    SendAuthReq* req =[[SendAuthReq alloc]init];
    req.scope = @"snsapi_userinfo";
    req.state = @"123";
    self->authHandler = completionHandler;
    //第三方向微信终端发送一个SendAuthReq消息结构
    [WXApi sendAuthReq:req viewController:nil delegate:self completion:nil];
}

-(void)AuthorizedWithUserInfo:(NSDictionary *)userInfo
        withCompletionHandler:(SocialRequestCompletionHandler)completionHandler{
    SocialAuthResponse *response = [[SocialAuthResponse alloc] init];
    NSError *err = [NSError errorWithDomain:@"weixin auth" code:10 userInfo:nil];
    completionHandler(response,err);
}

-(void)ShareWithObject:(SocialMessageObject *)object
 withCompletionHandler:(SocialRequestCompletionHandler)completionHandler{
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.bText = YES;
    req.text = object.title;
    req.scene = WXSceneSession;
    if ([object.shareObject isKindOfClass:[ShareImageObject class]]){
        // 图片分享
        ShareImageObject* temp = (ShareImageObject*)object.shareObject;
        UIImage *image = [UIImage imageNamed:temp.shareImage];
        
        WXImageObject *imageObject = [WXImageObject object];
        imageObject.imageData = UIImageJPEGRepresentation(image, 0.7);;
        
        WXMediaMessage *message = [WXMediaMessage message];
        message.thumbData = [NSData dataWithContentsOfFile:temp.shareImage];
        message.mediaObject = imageObject;
        
        req.bText = NO;
        req.message = message;
    }else if([object.shareObject isKindOfClass:[ShareVideoObject class]]){
        // 视频分享
        ShareVideoObject* temp = (ShareVideoObject*)object.shareObject;
        WXVideoObject *videoObject = [WXVideoObject object];
        videoObject.videoUrl = temp.videoUrl;
        videoObject.videoLowBandUrl = temp.videoLowBandUrl;
        
        WXMediaMessage *message = [WXMediaMessage message];
        message.title = temp.title;
        message.description = temp.description;
        [message setThumbImage:[UIImage imageNamed:temp.thumbImage]];
        message.mediaObject = videoObject;
        
        req.bText = NO;
        req.message = message;
    }else if([object.shareObject isKindOfClass:[ShareMiniProgramObject class]]){
        // 小程序分享
        ShareMiniProgramObject* temp = (ShareMiniProgramObject*)object.shareObject;
        WXMiniProgramObject *program = [WXMiniProgramObject object];
        program.webpageUrl = temp.webpageUrl;
        program.userName = temp.userName;
        program.path = temp.path;
        
        WXMediaMessage *message = [WXMediaMessage message];
        message.title = temp.title;
        message.description = temp.description;
        message.thumbData = nil;  //兼容旧版本节点的图片，小于32KB，新版本优先
        //使用WXMiniProgramObject的hdImageData属性
        message.mediaObject = program;
        
        req.bText = NO;
        req.message = message;
    }else if([object.shareObject isKindOfClass:[ShareWebpageObject class]]){
        // 网页分享
        ShareWebpageObject* temp = (ShareWebpageObject*)object.shareObject;
        WXWebpageObject *webpageObject = [WXWebpageObject object];
        webpageObject.webpageUrl = temp.webpageUrl;
        
        WXMediaMessage *message = [WXMediaMessage message];
        message.title = temp.title;
        message.description = temp.description;
        [message setThumbImage:[UIImage imageNamed:temp.thumbImage]];
        message.mediaObject = webpageObject;
        
        req.bText = NO;
        req.message = message;
    }
    [WXApi sendReq:req completion:nil];
}
-(void)LeaderboardWith:(NSString *)key withValue:(int) value
 withCompletionHandler:(SocialRequestCompletionHandler)completionHandler{
    NSError *err = [NSError errorWithDomain:@"weixin leaderboard" code:10 userInfo:nil];
    completionHandler(nil, err);
}
-(void)AchievementWith:(NSString *)key withValue:(int) value
 withCompletionHandler:(SocialRequestCompletionHandler)completionHandler{
    NSError *err = [NSError errorWithDomain:@"weixin achievement" code:10 userInfo:nil];
    completionHandler(nil, err);
}

/**
 *  获得从sso或者web端回调到本app的回调
 *
 *  @param url 第三方sdk的打开本app的回调的url
 *
 *  @return 是否处理  YES代表处理成功，NO代表不处理
 */
-(BOOL)handleOpenURL:(NSURL *)url{
    return [WXApi handleOpenURL:url delegate:self];
}
-(BOOL)handleOpenURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    return [WXApi handleOpenURL:url delegate:self];
}
-(BOOL)handleOpenURL:(NSURL *)url options:(NSDictionary*)options{
    return [WXApi handleOpenURL:url delegate:self];
}

-(BOOL)isInstall{
    return [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"wechat://"]];
//    return [WXApi isWXAppInstalled];
    //    return [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%d://",self->_appKey,0]]];
}
-(BOOL)isSupport{
    return [self isInstall];
}

-(BOOL)isLeaderboard{
    return false;
}
-(BOOL)isAchievement{
    return false;
}
-(void) onReq:(BaseReq*)req
{
    NSLog(@"weixin login req");
    if([req isKindOfClass:[GetMessageFromWXReq class]])
    {
        //        // 微信请求App提供内容， 需要app提供内容后使用sendRsp返回
        //        NSString *strTitle = [NSString stringWithFormat:@"微信请求App提供内容"];
        //        NSString *strMsg = @"微信请求App提供内容，App要调用sendResp:GetMessageFromWXResp返回给微信";
        //        [WXApi sendResp:nil];
    }
    else if([req isKindOfClass:[ShowMessageFromWXReq class]])
    {
        //        ShowMessageFromWXReq* temp = (ShowMessageFromWXReq*)req;
        //        WXMediaMessage *msg = temp.message;
        //
        //        //显示微信传过来的内容
        //        WXAppExtendObject *obj = msg.mediaObject;
        //
        //        NSString *strTitle = [NSString stringWithFormat:@"微信请求App显示内容"];
        //        NSString *strMsg = [NSString stringWithFormat:@"标题：%@ \n内容：%@ \n附带信息：%@ \n缩略图:%u bytes\n\n", msg.title, msg.description, obj.extInfo, msg.thumbData.length];
        
    }
    else if([req isKindOfClass:[LaunchFromWXReq class]])
    {
        //        //从微信启动App
        //        NSString *strTitle = [NSString stringWithFormat:@"从微信启动"];
        //        NSString *strMsg = @"这是从微信启动的消息";
        
    }
}

-(void) onResp:(BaseResp*)resp
{
    NSLog(@"weixin login resp");
    if([resp isKindOfClass:[SendMessageToWXResp class]])
    {
        SendMessageToWXResp* temp = (SendMessageToWXResp*)resp;
        SocialShareResponse *response = [[SocialShareResponse alloc]init];
        response.originalResponse = temp;
        NSError *err;
        response.message = temp.errStr;
        if(temp.errCode != 0){
            err = [NSError errorWithDomain:@"weixin share" code:temp.errCode userInfo:nil];
        }
        self->shareHandler(response, err);
    }
    else if ([resp isKindOfClass:[SendAuthResp class]])
    {
        SendAuthResp* temp = (SendAuthResp*)resp;
        SocialAuthResponse *response = [[SocialAuthResponse alloc] init];
        response.originalResponse = temp;
        NSError *err;
        if(temp.errCode!=0){
            err = [NSError errorWithDomain:@"weixin auth" code:temp.errCode userInfo:nil];
        }else{
            response.code = temp.code;
            response.state = temp.state;
        }
        self->authHandler(response,err);
    }
}
@end
